"""
* 首页: https://www.bjjnts.cn/mine/student/study

# 数据挖掘 13.7                    # course_id=273&unit_id=6203&class_id=26983

# VR 8.7                          # course_id=462&unit_id=10421&class_id=26983

# 专业技术人员沟通技巧 18.4         # class_id=26983&course_id=885&unit_id=14315

# 建筑 23.2                       # class_id=26983&course_id=2503&unit_id=35155

# 沟通的艺术 1.4                   # class_id=26983&course_id=884&unit_id=14288

# 管理沟通与领导力 1.6              # class_id=26983&course_id=873&unit_id=14251

--- 66课时
"""


from bdtime import tt
from temp import Robot, get_flag, WebDriver, save_ls, get_ls


# --- 读取参数文本
use_flag = get_ls('parameters.txt')[0] if get_ls('parameters.txt') else None
if use_flag:
    print('--- 加载配置文本parameters.txt')
    unit_id_ls = [0, 1]
    use_flag, username, password, class_id, course_id, unit_id_ls[0], unit_id_ls[1] = get_ls('parameters.txt')

# --- 其它参数
MAX_TIME = 60 * 60 * 8      # 最大运行时间


print(f'一共有: {unit_id_ls[1] - unit_id_ls[0] + 1}集, 范围: {unit_id_ls}')
base_url = f'https://www.bjjnts.cn/study/video?class_id={class_id}&course_id={course_id}&unit_id='


if __name__ == '__main__':
    robot = Robot(username=username, password=password)
    # robot.close()

    robot.sleep(20)
    robot.login()

    print('--- chrome_driver初始化完毕 ---')

    robot.confirm_threading()

    info_ls = get_ls()
    unit_id_start = unit_id_ls[0]       # 根据缓存判断是否重新开始
    if info_ls:
        unit_id_i_get, unit_id_0_get, unit_id_1_get, course_id_get, class_id_get = info_ls       # 当前集数
        if course_id == course_id_get and class_id_get == class_id_get:
            if unit_id_i_get > unit_id_start:
                unit_id_start = unit_id_i_get + 1
                print('~~~~~~~ 加载播放缓存')

    auto_next = True
    print(f'******* --- 开始范围: {unit_id_start, unit_id_ls[1]}', f'一共有: {unit_id_ls[1] - unit_id_start}集')

    first_get_url_i = True
    tt.__init__()
    for unit_id_i in range(unit_id_start, unit_id_ls[1]+1):
        print('********* unit_id_i: ', unit_id_i)

        try:
            robot.sleep(8)
            url_i = base_url + str(unit_id_i)
            robot.get_url_i(url_i)

            robot.sleep(8)
            robot.brush_one(url_i, auto_next=auto_next)
            robot.sleep(3)

            info_ls = [unit_id_i, unit_id_ls[0], unit_id_ls[1], course_id, class_id]  # 脚本当前信息
            save_ls(info_ls)

        except:
            info_ls = [unit_id_i, unit_id_ls[0], unit_id_ls[1], course_id, class_id]  # 脚本当前信息
            print('出错了~', info_ls)

        if tt.exceed(MAX_TIME):
            print('--- 已达到最大时间: ', MAX_TIME)
            break

        if get_flag():
            break

        print('********* 下一个unit_id_i: ', unit_id_i+1)

    with open('flag.txt', 'w') as f:
        f.write('break')

    print('--- 主程序结束, 总运行时间: ', tt.now(2))
    1
    # /Users/mac/.virtualenvs/PycharmProjects/111/bin/python
    # * 首页: https://www.bjjnts.cn/mine/student/study
